# -*- coding: utf-8 -*-
# @Date    : 2017-05-23 22:05:10
# @Author  : fancy (fancy@thecover.co)

import socket

BUFSIZE = 1024
host = ''
port = 8888
ADDR = (host, port)

def main():
    addr = ('::1', 8001)
    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    sock.connect(addr)

    data = 'hello world'
    sock.send(data)
    data = sock.recv(1024)
    print data
    sock.close()
    # data = ''
    # tmp = sock.recv(1024)
    # while tmp:
    #     print tmp
    #     data += tmp
    #     tmp = sock.recv(1024)
    # print tmp
    # sock.close()


def udp_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client.sendto('hello kugou', (host, port))
    data, addr = client.recvfrom(BUFSIZE)
    print data
    client.close()

def tc_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(ADDR)
    client.send('hello world\r\n')
    print client.recv(BUFSIZE).strip()
    client.close()

def tstServTW_client():
    from twisted.internet import protocol, reactor

    class TSClnProtocol(protocol.Protocol):
        # def sendData(self):
        #     self.transport.write('hello world')

        def connectionMade(self):
            # self.sendData()
            self.transport.write('hello world')

        def dataReceived(self, data):
            print data
            self.transport.loseConnection()

    class TSClntFactory(protocol.ClientFactory):
        protocol = TSClnProtocol
        clientConnectionLost = clientConnectionFailed = \
            lambda self, connector, reason: reactor.stop()

    reactor.connectTCP(host, port, TSClntFactory())
    reactor.run()


if __name__ == '__main__':
    # main()
    # udp_client()
    # tc_client()
    tstServTW_client()
